import request from '@/api/request'
import type { FileInfo } from '@/types/file'

/**
 * 回收站API模块
 */

// ==================== 类型定义 ====================

/**
 * 回收站统计信息
 */
export interface TrashStats {
  totalFiles: number
  totalSize: number
  expiringSoon: number
}

/**
 * 还原文件请求
 */
export interface RestoreFilesRequest {
  fileIds: number[]
  restoreToRoot?: boolean
}

/**
 * 彻底删除文件请求
 */
export interface PermanentDeleteRequest {
  fileIds: number[]
}

/**
 * 回收站文件查询参数
 */
export interface TrashFilesQuery {
  page?: number
  size?: number
  sortBy?: string
  sortDir?: 'asc' | 'desc'
}

/**
 * 分页响应
 */
export interface PageResponse<T> {
  content: T[]
  totalElements: number
  totalPages: number
  size: number
  number: number
  first: boolean
  last: boolean
  empty: boolean
}

// ==================== API接口 ====================

/**
 * 获取回收站文件列表
 */
export const getTrashFiles = (params: TrashFilesQuery = {}) => {
  const {
    page = 0,
    size = 20,
    sortBy = 'deletedAt',
    sortDir = 'desc'
  } = params

  return request.get<PageResponse<FileInfo>>('/trash/files', {
    params: {
      page,
      size,
      sortBy,
      sortDir
    }
  })
}

/**
 * 获取回收站统计信息
 */
export const getTrashStats = () => {
  return request.get<TrashStats>('/trash/stats')
}

/**
 * 还原文件
 */
export const restoreFiles = (data: RestoreFilesRequest) => {
  return request.post<void>('/trash/restore', data)
}

/**
 * 彻底删除文件
 */
export const permanentDeleteFiles = (data: PermanentDeleteRequest) => {
  return request.delete<void>('/trash/permanent', { data })
}

/**
 * 清空回收站
 */
export const emptyTrash = () => {
  return request.delete<void>('/trash/empty')
}

// ==================== 便捷方法 ====================

/**
 * 还原单个文件
 */
export const restoreFile = (fileId: number, restoreToRoot = false) => {
  return restoreFiles({
    fileIds: [fileId],
    restoreToRoot
  })
}

/**
 * 彻底删除单个文件
 */
export const permanentDeleteFile = (fileId: number) => {
  return permanentDeleteFiles({
    fileIds: [fileId]
  })
}

/**
 * 批量还原文件到原位置
 */
export const batchRestoreToOriginal = (fileIds: number[]) => {
  return restoreFiles({
    fileIds,
    restoreToRoot: false
  })
}

/**
 * 批量还原文件到根目录
 */
export const batchRestoreToRoot = (fileIds: number[]) => {
  return restoreFiles({
    fileIds,
    restoreToRoot: true
  })
}

/**
 * 批量彻底删除文件
 */
export const batchPermanentDelete = (fileIds: number[]) => {
  return permanentDeleteFiles({
    fileIds
  })
}

// ==================== 工具函数 ====================

/**
 * 格式化删除时间
 */
export const formatDeletedTime = (deletedAt: string): string => {
  const date = new Date(deletedAt)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else if (diffDays < 30) {
    const weeks = Math.floor(diffDays / 7)
    return `${weeks}周前`
  } else {
    return `${Math.floor(diffDays / 30)}个月前`
  }
}

/**
 * 计算文件过期时间
 */
export const calculateExpiryTime = (deletedAt: string, retentionDays = 30): string => {
  const deletedDate = new Date(deletedAt)
  const expiryDate = new Date(deletedDate.getTime() + retentionDays * 24 * 60 * 60 * 1000)
  const now = new Date()
  
  if (expiryDate <= now) {
    return '已过期'
  }
  
  const diffMs = expiryDate.getTime() - now.getTime()
  const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) {
    return '明天过期'
  } else if (diffDays <= 7) {
    return `${diffDays}天后过期`
  } else {
    return `${Math.ceil(diffDays / 7)}周后过期`
  }
}

/**
 * 检查文件是否即将过期
 */
export const isExpiringSoon = (deletedAt: string, retentionDays = 30, warningDays = 7): boolean => {
  const deletedDate = new Date(deletedAt)
  const expiryDate = new Date(deletedDate.getTime() + retentionDays * 24 * 60 * 60 * 1000)
  const warningDate = new Date(expiryDate.getTime() - warningDays * 24 * 60 * 60 * 1000)
  const now = new Date()
  
  return now >= warningDate && now < expiryDate
}

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 获取文件类型图标
 */
export const getFileTypeIcon = (fileName: string, isDirectory: boolean): string => {
  if (isDirectory) {
    return 'folder'
  }
  
  const extension = fileName.split('.').pop()?.toLowerCase() || ''
  
  const iconMap: Record<string, string> = {
    // 图片
    jpg: 'image',
    jpeg: 'image',
    png: 'image',
    gif: 'image',
    bmp: 'image',
    svg: 'image',
    webp: 'image',
    
    // 文档
    pdf: 'pdf',
    doc: 'word',
    docx: 'word',
    xls: 'excel',
    xlsx: 'excel',
    ppt: 'powerpoint',
    pptx: 'powerpoint',
    txt: 'text',
    
    // 代码
    js: 'code',
    ts: 'code',
    html: 'code',
    css: 'code',
    java: 'code',
    py: 'code',
    cpp: 'code',
    c: 'code',
    
    // 音频
    mp3: 'audio',
    wav: 'audio',
    flac: 'audio',
    aac: 'audio',
    ogg: 'audio',
    
    // 视频
    mp4: 'video',
    avi: 'video',
    mkv: 'video',
    mov: 'video',
    
    // 压缩包
    zip: 'archive',
    rar: 'archive',
    '7z': 'archive',
    tar: 'archive',
    gz: 'archive'
  }
  
  return iconMap[extension] || 'file'
}
